import os
import shutil
from PIL import Image, ImageOps


def transform(input_dir, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for root, dirs, files in os.walk(input_dir):
        for file in files:
            # print("1111")
            filepath = os.path.join(root, file)
            filename, ext = os.path.splitext(file)

            if ext != '.png':
                newfile = filename + '.png'
                print('transform ' + file)

                image = Image.open(filepath)
                image = ImageOps.exif_transpose(image)

                # 将图像转换为灰度图像
                gray_image = image.convert('RGB')

                gray_image.save(os.path.join(output_dir, newfile))
            else:
                shutil.copy(filepath, os.path.join(output_dir, file))


if __name__ == '__main__':
    input_dir = '/media/jolly/HIK/Brain Tumor Segmentation Dataset/label/predictResult/'
    output_dir = '/media/jolly/HIK/Brain Tumor Segmentation Dataset/label/predictResult1/'

    if not os.path.exists(input_dir):
        print("文件夹不存在!")
    else:
        print("Start to transform!")
        transform(input_dir, output_dir)
        print("Transform end!")